package com.rss.provider.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.rss.provider.dao.RssDao;
import com.rss.provider.hibernate.entity.SubscriberEntity;
import com.rss.provider.hibernate.entity.UpdateEntity;
import com.rss.provider.service.RssService;
import com.rss.provider.spring.form.SubscriberForm;
import com.rss.provider.spring.form.UpdateForm;

@Service("RssServiceImpl")
@Transactional(propagation=Propagation.REQUIRED)
public class RssServiceImpl implements RssService {

	@Autowired
	@Qualifier("RssDaoImpl")
	private RssDao rssDao;
	
	@Override
	public String addSubscriber(SubscriberForm subscriberForm) {
		SubscriberEntity subscriberEntity = new SubscriberEntity();
		BeanUtils.copyProperties(subscriberForm, subscriberEntity);
		String result = rssDao.addSubscriber(subscriberEntity);
		return result;
	}

	@Override
	public String removeSubscriber(SubscriberForm unsubscriberForm) {
		SubscriberEntity unsubscriberEntity = new SubscriberEntity();
		BeanUtils.copyProperties(unsubscriberForm, unsubscriberEntity);
		String result = rssDao.removeSubscriber(unsubscriberEntity);
		return result;
	}

	@Override
	public List<SubscriberForm> getAllSubscribers(String subscribedTo) {
		List<SubscriberEntity> subscriberEntities = rssDao.getAllSubscribers(subscribedTo);
		List<SubscriberForm> subscriberForms = new ArrayList<SubscriberForm>();
		if(subscriberEntities == null){
			return null;
		}
		for (SubscriberEntity subscriberEntity : subscriberEntities) {
			SubscriberForm subscriberForm = new SubscriberForm();
			BeanUtils.copyProperties(subscriberEntity, subscriberForm);
			subscriberForms.add(subscriberForm);
		}
		return subscriberForms;
	}

	@Override
	public String saveUpdate(UpdateForm updateForm) {
		UpdateEntity updateEntity = new UpdateEntity();
		BeanUtils.copyProperties(updateForm, updateEntity);
		String result = rssDao.saveUpdate(updateEntity);
		return result;
	}

	@Override
	public List<UpdateForm> getUpdates(Date fromDate) {
		List<UpdateEntity> updateEntities = rssDao.getUpdates(fromDate);
		List<UpdateForm> updateForms = new ArrayList<UpdateForm>();
		if(updateEntities == null){
			return null;
		}
		for (UpdateEntity updateEntity : updateEntities) {
			UpdateForm updateForm = new UpdateForm();
			BeanUtils.copyProperties(updateEntity, updateForm);
			updateForms.add(updateForm);
		}
		return updateForms;
	}

}
